//
//  LYGuideViewController.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/19.
//

import UIKit

class LYGuideViewController: LYBaseViewController {
    
    lazy var tryButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle(LYlocalizedString("Try again"), for: .normal)
        button.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        button.layer.masksToBounds = true
        button.layer.borderColor = UIColor(hex: "#FFFFFF").cgColor
        button.backgroundColor = UIColor(hex: "#1E4FF3")
        button.layer.borderWidth = 1.0
        button.layer.cornerRadius = 22.5
        button.addTarget(self, action: #selector(tryRequestAction(_:)), for: .touchUpInside)
        button.isHidden = true
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.bgImage = UIImage(named: "background_guide")
        
        view.addSubview(tryButton)
        tryButton.snp.makeConstraints { make in
            make.height.equalTo(45)
            make.leading.trailing.equalToSuperview().inset(23)
            make.bottom.equalToSuperview().offset(-46 - bottomMargin)
        }
        
        if LYUserDefaults.shared.getBool(forKey: allowNetworkKey) != nil {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
                guard let self = self else { return }
                self.loadEnvironment()
            }
        } else {
            NetworkPermissionManager.shared.startMonitoring { grand in
                if grand {
                    self.loadEnvironment()
                    NetworkPermissionManager.shared.stopMonitoring()
                } else {
                    self.tryButton.isHidden = false
                }
            }
        }
    }
    
    func loadEnvironment() {
        LYHUDUtils.showLoading()
        LYStocksManager.fetchEnvironment { [weak self] env, msg, error in
            guard let self = self else { return }
            if error == nil {
                if let countryId = env?.diploon {
                    LYUserDefaults.shared.setString(countryId, forKey: countryIdKey)
                }
                self.changeRootViewController()
                LYHUDUtils.hideHUD()
            } else {
                tryButton.isHidden = false
                LYHUDUtils.showToast(msg)
            }
        }
    }
    
    @objc func tryRequestAction(_ sender: UIButton) {
        loadEnvironment()
    }
    
    func changeRootViewController() {
        guard let window = UIApplication.shared.currentKeyWindow else {
//            assertionFailure("无法获取当前key window")
            return
        }
        
        // 检查是否需要切换（避免不必要的视图控制器替换）
        let shouldShowLogin = !LYUserConfig.shared.isLogin
        let currentIsLoginVC = window.rootViewController is LYLoginViewController
        let currentIsMainVC = window.rootViewController is LYMainViewController
        
        // 如果当前已经是正确的视图控制器，则不需要切换
        if (shouldShowLogin && currentIsLoginVC) || (!shouldShowLogin && currentIsMainVC) {
            return
        }
        
        // 准备新的根视图控制器
        let newRootVC: UIViewController = {
            if LYUserConfig.shared.isLogin {
                let mainVC = LYMainViewController()
                return mainVC
            } else {
                return LYLoginViewController()
            }
        }()
        
        // 添加平滑过渡动画
        UIView.transition(with: window,
                         duration: 0.3,
                         options: .transitionCrossDissolve,
                         animations: {
                            window.rootViewController = newRootVC
                         },
                         completion: { _ in
                            window.makeKeyAndVisible()
                         })
    }
}
